import React from "react";
import { Button, Toast ,ProgressCircle} from "antd-mobile";
// 6.正确封装axios拦截器
import axios from "./request/index";
const App = () => {
  const [show, setShow] = React.useState(false)
  const [list,setList] = React.useState([])
  // 3.点击选择图片按钮正确完成图片上传
  const handleUpLoad = () => {
    const input = document.createElement("input");
    input.type = "file";
    // 4.图片上传需要对文件的大小及格式进行验证
    input.size = 1;
    input.accept = "image/*";
    input.click();
    input.onchange = () => {
      let file = input.files[0];
      // 5.正确考虑选择数据为空情况处理
      if (!file) {
        return Toast.show("请选择图片");
      }
      setShow(true);
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const base64 = reader.result;
        // 10.将上传的图片文件转换为数据URL对图片进行预处理
        const base64Index = base64.indexOf(",") + 1;
        const base64Str = base64.substring(base64Index);
        // 7.正确完成服务器上传图片
        async function main() {
          var options = {
              'method': 'POST',
              'url': '/baidu/rest/2.0/ocr/v1/accurate_basic?access_token=' + await getAccessToken(),
              'headers': {
                      'Content-Type': 'application/x-www-form-urlencoded',
                      'Accept': 'application/json'
              },
              data: {
                      'image': base64Str,
                      'detect_direction': 'false',
                      'paragraph': 'false',
                      'probability': 'false',
                      'multidirectional_recognize': 'false'
              }
          };
      
          axios(options)
              .then(response => {
                // 11.正确实现图像进行OCR识别，识别过程中，实时更新进度条。
                console.log(response.data.words_result);
                  setList(response.data.words_result);
                  setShow(false);

              })
              // 8.正确完成上传失败图片进行提示
              .catch(error => {
                setShow(false);
                  throw new Error(error);
                  
              })
      }
      main();
      
      };
    };
  };
  function getAccessToken() {
    const AK = "eTUlpTQ6VnLEYRwA6RydTe1j";
    const SK = "qVZ8Mlu7sWhr6p9lxMLZT4bevPIqeWT2";
    let options = {
      method: "POST",
      url:
        "/baidu/oauth/2.0/token?grant_type=client_credentials&client_id=" +
        AK +
        "&client_secret=" +
        SK,
    };
    return new Promise((resolve, reject) => {
      axios(options)
        .then((res) => {
          resolve(res.data.access_token);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
  return (
    <div>
      <div className="textBox">
        <h3>文字识别结果:</h3>
        {
           show&&
           <ProgressCircle percent={80} />
        }
        {
          <ul>
            {
              list.map((item, index) => {
                return <li key={index}>{item.words}</li>
              })
            }
          </ul>
        }
      </div>
      <Button
        type="primary"
        onClick={handleUpLoad}
        color="primary"
        style={{
          position: "fixed",
          bottom: "50%",
          left: "30%",
        }}
      >
        图片上传文字识别
      </Button>
    </div>
  );
};

export default App;
